/*
 * Created on Mar 29, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author U678864
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

package com.jjprojects.earutility;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.swing.*;

import javax.swing.JTree;
import javax.swing.tree.*;

import java.io.BufferedWriter;

public class EARFileViewingTool implements ActionListener
{
    static Cursor curHand = new Cursor(Cursor.HAND_CURSOR);
    LinkedHashMap lnkhmapFullEARDetails = new LinkedHashMap();

    static JDialog dlgEARExploreTool = null;
    
    JTree treeEARFileDetails = null;
    DefaultMutableTreeNode root = null;
    JButton btnClose = null;
    JScrollPane jspRecycleBinManager = null;
    String strGlobleCurrentFileDestinationPath = null;
    String strGlobleCurrentSelectedEARFile = null;
    JTextArea txtaraTreeNodeDetails = null;
    
    String strLastSelectedNode = null;
    String strCurrentSelectedNode= null;
    
    DefaultMutableTreeNode[] dmtnodeCurrent = new DefaultMutableTreeNode[10000];
    int intTreeRowCount = 0;
    
    public void showEARExploreDialog(String strEARFile)
    {
        strGlobleCurrentSelectedEARFile = strEARFile;
        dlgEARExploreTool = new JDialog(EARUtility.frmEARUtility, "EAR Explorer", true);
        
        treeEARFileDetails = new JTree(new DefaultMutableTreeNode());
        treeEARFileDetails.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        treeEARFileDetails.setCellRenderer(new CustomTreeRenderer(this,1));
        jspRecycleBinManager = new JScrollPane(
                treeEARFileDetails, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        dlgEARExploreTool.add(jspRecycleBinManager);
        
        DefaultMutableTreeNode root = new DefaultMutableTreeNode();
        treeEARFileDetails = new JTree(new DefaultMutableTreeNode());
        treeEARFileDetails.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        treeEARFileDetails.setCellRenderer(new CustomTreeRenderer(this,1));
        
        String strFileDestinationPath = "\\Temp\\" + new Date().getTime() + "/";
        extractCurrentFile(strEARFile, strFileDestinationPath);
        
        root = showFiles(root, strFileDestinationPath);
        root.setUserObject(strEARFile);
        treeEARFileDetails = new JTree(root);

        treeEARFileDetails.setCursor(curHand);

        treeEARFileDetails.setBackground(Color.WHITE);
		
		treeEARFileDetails.addMouseListener(new MouseAdapter()
		{
		    public void mouseClicked(MouseEvent e)
			{}
		});
		
        btnClose = new JButton("Close");
        btnClose.addActionListener(this);
        jspRecycleBinManager = new JScrollPane(
                treeEARFileDetails, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        
        txtaraTreeNodeDetails = new JTextArea();
        JScrollPane jspTreeNodeDetails = new JScrollPane(
                txtaraTreeNodeDetails, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        
        JSplitPane spltpanEARFileView = new JSplitPane(
                JSplitPane.HORIZONTAL_SPLIT, false, jspRecycleBinManager,
                jspTreeNodeDetails);
        
        spltpanEARFileView.setDividerLocation(300);
        spltpanEARFileView.setDividerSize(2);
        dlgEARExploreTool.getContentPane().add(spltpanEARFileView);
        
        dlgEARExploreTool.add(spltpanEARFileView, BorderLayout.CENTER);
        
        JPanel panlButton = new JPanel();
        panlButton.setLayout(new FlowLayout(FlowLayout.RIGHT));
        panlButton.add(btnClose);
        
        dlgEARExploreTool.add(panlButton, BorderLayout.NORTH);

        dlgEARExploreTool.setSize(EARUtility.intActualWidth, EARUtility.intActualHeight);
        
        dlgEARExploreTool.setVisible(true);
    }
    
    public DefaultMutableTreeNode showFiles(DefaultMutableTreeNode dmtnodeParent, String strCurrentFileStructure)
    {
        File fileCurrent = new File(strCurrentFileStructure);
        
        File[] filearrCurrentChilds = fileCurrent.listFiles();
        
        for(int i=0;i<filearrCurrentChilds.length;i++)
        {
            if(filearrCurrentChilds[i].isDirectory())
            {
                String strCurrentFile = filearrCurrentChilds[i].toString();
                int intLastSlashIndex = strCurrentFile.lastIndexOf("\\");
                String strCurrentFileNameAlone = strCurrentFile.substring(++intLastSlashIndex);
                dmtnodeCurrent[intTreeRowCount] = new DefaultMutableTreeNode(strCurrentFileNameAlone);
                dmtnodeParent.add(dmtnodeCurrent[intTreeRowCount]);
                intTreeRowCount++;
                getChildNodeDetails(dmtnodeCurrent[(intTreeRowCount - 1)], filearrCurrentChilds[i]);
            }
            else
            {
                String strCurrentFile = filearrCurrentChilds[i].toString();
                int intLastSlashIndex = strCurrentFile.lastIndexOf("\\");
                String strOnlyFileName = strCurrentFile.substring(++intLastSlashIndex);
                dmtnodeCurrent[intTreeRowCount] = new DefaultMutableTreeNode(strOnlyFileName);
                dmtnodeParent.add(dmtnodeCurrent[intTreeRowCount]);
            }
        }
        return dmtnodeParent;
    }
    
    public void getChildNodeDetails(DefaultMutableTreeNode dmtnodeParent, File fileCurrent)
    {
        File[] filearrCurrentChildNodes = fileCurrent.listFiles();
        for(int i=0;i<filearrCurrentChildNodes.length;i++)
        {
            if(filearrCurrentChildNodes[i].isDirectory())
            {
                String strCurrentFile = filearrCurrentChildNodes[i].toString();
                int intLastSlashIndex = strCurrentFile.lastIndexOf("\\");
                String strCurrentFileNameAlone = strCurrentFile.substring(++intLastSlashIndex);
                
                dmtnodeCurrent[intTreeRowCount] = new DefaultMutableTreeNode(strCurrentFileNameAlone);
                dmtnodeParent.add(dmtnodeCurrent[intTreeRowCount]);
                intTreeRowCount++;
                getChildNodeDetails(dmtnodeCurrent[(intTreeRowCount - 1)], filearrCurrentChildNodes[i]);
            }
            else
            {
                String strCurrentFile = filearrCurrentChildNodes[i].toString();
                int intLastSlashIndex = strCurrentFile.lastIndexOf("\\");
                String strOnlyFileName = strCurrentFile.substring(++intLastSlashIndex);
                
                dmtnodeCurrent[intTreeRowCount] = new DefaultMutableTreeNode(strOnlyFileName);
                dmtnodeParent.add(dmtnodeCurrent[intTreeRowCount]);
                intTreeRowCount++;
            }
        }
    }
    
    public void extractCurrentFile(String strEarFilePathAndName, String strFileDestinationPath)
    {
        try
        {
            // Open the ZIP file
            ZipInputStream in = new ZipInputStream(new FileInputStream(strEarFilePathAndName));

            // Get the first entry
            ZipEntry entry = in.getNextEntry();
            int i = 0;
            
            while(entry != null)
            {
                String strZipFileEntity = entry.getName();
                
                
                if(!(strZipFileEntity.contains(".")))
                {
                    entry = in.getNextEntry();
                    continue;
                }
                //Check for destination path
                File fileDestination = new File(strFileDestinationPath);
                boolean boolDestinationAlreadyExists = fileDestination.exists();
//                boolDestinationAlreadyExists);
                if(!boolDestinationAlreadyExists)
                {
                    boolean boolProjectCreated = fileDestination.mkdir();
//                    "boolProjectCreated = " + boolProjectCreated);
                }
                
                //Open the output file
                String strFileNameAndDirectoryWithoutDrive = strEarFilePathAndName.substring(2); 
                String strOutputFileName = fileDestination + "/" + strZipFileEntity;
//                "strOutputFileNamestrOutputFileName->" + strOutputFileName);
                //Check for existince
                int intLastIndex = strOutputFileName.lastIndexOf("/");
                if(intLastIndex >= 0)
                {
                    String strOnlyDirectory = strOutputFileName.substring(0, ++intLastIndex);
//                    "!!!!!!!!!!!!!" + strOnlyDirectory);
                    File fileToCheck = new File(strOnlyDirectory);
                    if(!(fileToCheck.exists()))
                    {
                        fileToCheck.mkdirs();
                    }
                }
                OutputStream out = new FileOutputStream(strOutputFileName);
                
                // Transfer bytes from the ZIP file to the output file
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0)
                {
                    out.write(buf, 0, len);
                }
                i++;
                
                out.close();
                entry = in.getNextEntry();
            }
            in.close();
        }
        catch (IOException e)
        {
            EARUtility.log4jEARUtility.fatal("Exception", e);
        }
    }
    
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == btnClose)
        {
            dlgEARExploreTool.setVisible(false);
        }
    }
    
    
    public static void main(String[] args)
    {
        new EARFileViewingTool().showEARExploreDialog("JPMCDEPENDENTS.jar");
    }
}